#include "adddialog.h"
#include "ui_adddialog.h"

#include <QMessageBox>


AddDialog::AddDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::AddDialog)
{
    ui->setupUi(this);
}

AddDialog::~AddDialog()
{
    delete ui;
}

int AddDialog::countSql(QSqlQuery query)
{
    int count = 0;
    while(query.next())
    {
        count += 1;
    }
    query.first();
    return count;
}

void AddDialog::on_buttonBox_clicked(QAbstractButton *button)
{
    // connect sqlite
//    db = QSqlDatabase::addDatabase("QSQLITE");
//    db.setDatabaseName("money.db");
//    if(!db.open())
//    {
//        qDebug() << "database error!";
//    }

    if(button->text() == "OK")
    {
        QString name = ui->nameLineEdit->text();
        QString money = ui->moneyLineEdit->text();
        QSqlQuery query;
        QString qry_ct = "select * from user where username='" + name +"';";
        QByteArray ay_ct = qry_ct.toUtf8();
        query.exec(QObject::tr(ay_ct.data()));
//        qDebug() << countSql(query);
        if(countSql(query))
        {
            QMessageBox msgBox;
            msgBox.setText("姓名重覆！");
            msgBox.exec();
        }
        else
        {
            QString inStr = "insert into user (username,money) values ('" + name + "'," + money + ");";
            qDebug() << inStr;
            QByteArray ay_is = inStr.toUtf8();
            query.exec(QObject::tr(ay_is.data()));
            QMessageBox msgBox;
            msgBox.setText("insert成功！");
            msgBox.exec();
            emit UpdateComBox();
        }
    }
}
